/** 
 * cocos动态加载全局公用图片资源 
 * eg: 货币资源、道具资源等
 */

import DebugExt from "./DebugExt";

export default class GlobalImg {

    public static getIns(): GlobalImg {
        if (!GlobalImg._ins) {
            GlobalImg._ins = new GlobalImg();
        }
        return GlobalImg._ins;
    }
    private static _ins: GlobalImg;

    /**
     * 初始化全局图片资源
     * @param filePath 默认资源目录，暂不支持嵌套目录
     */
    public init(filePath: string) {
        this._filePath = filePath || "";
        this._filePath = this._filePath.trim();
        if (this._filePath && this._filePath.length > 0) {
            this.loadResDir(this._filePath, null);
        }
    }
    private _filePath: string = "";

    private constructor() {
    }
    private onDestory() {
        this._iconList.clear();
    }

    public static destory() {
        if (GlobalImg._ins) {
            GlobalImg._ins.onDestory();
            delete GlobalImg._ins;
            GlobalImg._ins = null;
        }
    }

    private loadResDir(path: string, completeCallback: (loaded: boolean) => void) {
        cc.loader.loadResDir(path, cc.SpriteFrame, (error: Error, resource: cc.SpriteFrame[], urls: string[]) => {
            if (error || resource.length == 0) {
                DebugExt.debug("【GlobalImg】加载资源目录:", path, "出错！", error ? error.message : "空文件夹！");
                if (completeCallback)
                    completeCallback(false);
            }
            else {
                resource.forEach((icon: cc.SpriteFrame) => {
                    if (icon && icon.isValid)
                        this._iconList.set(icon.name, icon);
                });
                DebugExt.debug("【GlobalImg】加载资源目录:", path, "完成！");
                DebugExt.table(this._iconList);
                if (completeCallback)
                    completeCallback(true);
            }
        });
    }

    // resource map
    private _iconList: Map<string, cc.SpriteFrame> = new Map();
    /**
     * 获取指定名称的图片资源
     * @param name 图片资源名
     */
    public getIcon(name: string): cc.SpriteFrame {
        if (!name || name.length == 0)
            return null;
        return this._iconList.get(name);
    }

}
